import React, { useState, useEffect } from 'react'
import { Table, Tag, Button, Modal, Popover, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';


import axios from 'axios';
const { confirm } = Modal;
export default function RightList() {
  const [data, setData] = useState([])
  // 获取所有权限
  useEffect(() => {
    axios.get('/rights?_embed=children').then(res => {
      let list = res.data;
      // 把请求回来的数据-->"首页"children属性赋值为空字符串，本身是[]，这样的话渲染UI时，首页也有展开项，赋值为""，只要不是数组就不会有展开项了
      list.forEach(item => {
        if (item.children.length === 0) {
          item.children = ''
        }
      })
      setData(list)
    })
  }, [])
     // 药丸事件
     function switchMethod(row){
         row.pagepermisson=row.pagepermisson===1? 0 : 1;
         setData([...data])
         if(row.grade===1){
          axios.patch(`/rights/${row.id}`,{
            pagepermisson:row.pagepermisson
          })
         }else{  //grade===2代表是二级菜单
          axios.patch(`/children/${row.id}`,{
            pagepermisson:row.pagepermisson
          })
         }
    }
  // 表格头设置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => <b>{id}</b>
    },
    {
      title: '权限名称',
      dataIndex: 'label',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (key) => <Tag color="orange">{key}</Tag>
    },
    {
      title: '操作',
      render: (row) => {
        return <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(row)} />
          <Popover content={<div><Switch checked={row.pagepermisson} onChange={()=>switchMethod(row)}></Switch></div>} title="配置项" trigger={row.pagepermisson === undefined ? '' : 'click'}>
            <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={row.pagepermisson === undefined} />
          </Popover>
        </div>
      }
    }
  ]

  // 删除事件
  function confirmMethod(row) {
    confirm({
      title: '你确定删除当前项吗？',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        // 过滤出所有权限和当前项权限id不相等的元素，并更改状态，为了前后台同步，需要再次发请求修改后端数据
        if (row.grade === 1) { //说明是一级菜单
          setData(data.filter(item => item.id !== row.id))
          axios.delete(`/rights/${row.id}`)
        } else {
          //如果被点击的"删除"按钮是二级菜单的化，那么需要通过二级菜单找到一级菜单----注意下面find得到的是数据的引用，浅拷贝
          let list = data.find(item => item.id === row.rightId)
          // 在一级菜单children里过滤掉当前传进来的row
          list.children = list.children.filter(item => item.id !== row.id)
          //在这里用深拷贝展开
          setData([...data]);
          axios.delete(`/children/${row.id}`)
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
 
  return (
    <Table
      pagination={{ pageSize: 5 }}
      columns={columns}
      dataSource={data}
    />
  )
}
